package com.example.pungolo.journal;

import java.io.File;
import java.util.Date;

import com.example.pungolo.journal.model.DiaryIO;
import com.example.pungolo.journal.model.DiaryPage;
import com.example.pungolo.journal.view.BitmapWorkerTask;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Point;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class CameraActivity extends Activity {

  private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 1;
  private static final int CROP_IMAGE_ACTIVITY_REQUEST_CODE = 6;
  private String originalImagePath;
  private String newImagePath;

  private boolean edited = false;
  AlertDialog.Builder cancelAlertBuilder;
  private int[] cropData = null;
  private ImageView photoView;
  private Uri newImageUri;

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_camera);

    final Button saveButton = (Button) findViewById(R.id.cameraUI_save);
    final Button cancelButton = (Button) findViewById(R.id.cameraUI_cancel);
    final Button cropButton = (Button) findViewById(R.id.cameraUI_crop);
    final Button takePhotoButton = (Button) findViewById(R.id.cameraUI_takePhoto);

    cancelButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { onBackPressed(); } });
    cropButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { onCropButtonClicked(); } });
    saveButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { onSaveButtonClicked(); } });
    takePhotoButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { onTakePhotoButtonClicked(); } });
    cancelAlertBuilder = new AlertDialog.Builder(this);
    cancelAlertBuilder.setMessage("Are you sure you want to lose all the changes you made?");
    cancelAlertBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface arg0, int arg1) {
        onForceExitClicked();
      }
    });
    cancelAlertBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface arg0, int arg1) {
      }
    });

    Intent caller = getIntent();
    if (caller.hasExtra("imagePath"))
      originalImagePath = caller.getStringExtra("imagePath");
    if (caller.hasExtra("cropData"))
      cropData = caller.getIntArrayExtra("cropData");

    if (savedInstanceState != null) {
      if (savedInstanceState.containsKey("imagePath"))
        newImagePath = savedInstanceState.getString("imagePath");
      if (savedInstanceState.containsKey("cropData"))
        cropData = savedInstanceState.getIntArray("cropData");
      if (savedInstanceState.containsKey("edited"))
        edited = savedInstanceState.getBoolean("edited");
    }

    // set image
    this.photoView = (ImageView) findViewById(R.id.cameraUI_pictureView);
    updateImageView();

    if (originalImagePath == null)
      start_camera();
  }

  private void updateImageView() {
    photoView.post(new Runnable() {
      public void run() {
        Rect rect = DiaryPage.getCropRect(cropData);
        Point size = new Point(photoView.getWidth(), photoView.getHeight());
        Button cropButton = (Button) findViewById(R.id.cameraUI_crop);
        Button saveButton = (Button) findViewById(R.id.cameraUI_save);
        if (newImagePath != null) {
          saveButton.setEnabled(true);
          cropButton.setEnabled(true);

          BitmapWorkerTask task = new BitmapWorkerTask(photoView, size, rect);
          task.execute(newImagePath);
        } else if (originalImagePath != null) {
          if (new File(originalImagePath).exists()) {
            photoView.setImageResource(R.drawable.loading_photo);
            BitmapWorkerTask task = new BitmapWorkerTask(photoView, size, rect);
            task.execute(originalImagePath);
          } else {
            photoView.setImageResource(R.drawable.notfound_photo);

            cropButton.setEnabled(false);
            saveButton.setEnabled(false);
          }
        } else {
          photoView.setImageResource(R.drawable.default_photo);

          cropButton.setEnabled(false);
          saveButton.setEnabled(false);
        }
      }
    });
  }

  protected void onSaveInstanceState(Bundle icicle) {
    super.onSaveInstanceState(icicle);
    icicle.putString("imagePath", newImagePath);
    icicle.putIntArray("cropData", cropData);
    icicle.putBoolean("edited", edited);
  }

  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
      if (resultCode != RESULT_OK)
        return;
      U.delete(newImagePath);

      newImagePath = newImageUri.getPath();
      cropData = null;
      updateImageView();
      edited = true;
    }

    else if (requestCode == CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
      if (resultCode != RESULT_OK)
        return;
      if (data == null || !data.hasExtra("cropData"))
        throw new IllegalArgumentException();
      cropData = data.getIntArrayExtra("cropData");
      updateImageView();
      edited = true;
    }
  }

  public void onBackPressed() {
    if (edited)
      cancelAlertBuilder.show();
    else
      onForceExitClicked();
  }

  protected void onSaveButtonClicked() {
    String path;
    if (newImagePath == null)
      path = originalImagePath;
    else
      path = newImagePath;

    Intent back = new Intent();
    back.putExtra(android.content.Intent.EXTRA_TEXT, path);
    back.putExtra("cropData", cropData);
    this.setResult(RESULT_OK, back);
    finish();
  }

  protected void onCropButtonClicked() {
    Intent cropIntent = new Intent(getApplicationContext(), CropActivity.class);
    cropIntent.putExtra("picturePath", newImagePath == null ? originalImagePath : newImagePath);
    cropIntent.putExtra("cropData", cropData);
    startActivityForResult(cropIntent, CROP_IMAGE_ACTIVITY_REQUEST_CODE);
  }

  protected void onTakePhotoButtonClicked() {

    start_camera();
  }

  protected void onForceExitClicked() {
    U.delete(newImagePath);
    super.onBackPressed();
  }

  private void start_camera() {
    Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    File dir = DiaryIO.getDiaryDirectory();
    File photo = new File(dir, new Date().getTime() + ".jpg");
    newImageUri = Uri.fromFile(photo);
    Log.w("newImageUri", newImageUri.getPath());
    camera.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo)); // set
    // the
    // image
    // file
    // name

    // start the image capture Intent
    startActivityForResult(camera, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);

  }

}